package com.qsmx.store.app.widget;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.widget.Toast;

import com.qsmx.store.core.event.QrScanEvent;
import com.qsmx.store.core.fusion.FusionCode;
import com.qsmx.store.core.fusion.FusionString;

import org.greenrobot.eventbus.EventBus;

/**
 * Created by Heyiyong on 2014-2-19 上午12:20.
 */
public class MyDialog extends Dialog {

    private final StringBuilder sb = new StringBuilder();
    private static final int END_CHAR_ID = 66;
    private static final int BLANK_CHAR_ID = 59;

    private Context mContext;

    public MyDialog(Context context, int theme) {
        super(context, theme);
        mContext = context;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        System.out.println("keycode=========>" + keyCode + "");
        char keyValue = (char) event.getUnicodeChar();
        // 生成二维码有大写字母的时候，会有空格出现，这个就是过滤空格的
        if (keyCode != END_CHAR_ID && keyCode != BLANK_CHAR_ID) {
            sb.append(keyValue);
        } else if (!TextUtils.isEmpty(sb.toString()) && keyCode != BLANK_CHAR_ID) {

            if (!FusionCode.QrIsLoading) {
                FusionCode.QrIsLoading = true;
                String qrCode = sb.toString().trim().replaceAll("\\s*", "");

                Bundle bundle = new Bundle();
                bundle.putString(FusionString.QR_CODE, qrCode);
                EventBus.getDefault().removeAllStickyEvents();
                EventBus.getDefault().postSticky(new QrScanEvent(bundle));

                sb.setLength(0);
            }
        }

        // 结束符去掉，不然有的界面不需要扫描功能，导致它扫描都内容叠加
        if (keyCode == END_CHAR_ID) {
            sb.setLength(0);
        }

        return super.onKeyDown(keyCode, event);
    }
}